package com.example.domain;

import com.alibaba.fastjson2.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;

@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    private User user;

    private List<String> permissions;

    /**
     * 告诉 fastjson2 序列化时忽略这个字段
     * 结果是：Redis 里根本不会存 authorities，反序列化后这个字段为 null
     * 所以你只要依赖 Redis 反序列化还原出 authorities，一定会失败
     */
    // 存储SpringSecurity所需要的权限信息
    @JSONField(serialize = false) // 忽略此字段序列化
    private List<SimpleGrantedAuthority> authorities;

    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }

    /**
     * 获取用户权限
     *
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 将权限信息封装成SimpleGrantedAuthority
        if (authorities != null) { // 懒加载
            return authorities;
        }
        authorities = permissions.stream()
                .distinct() // 去重
                .map(SimpleGrantedAuthority::new)
                .toList();
        return authorities;
    }

    /**
     * 获取用户密码
     *
     * @return
     */
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    /**
     * 获取用户名
     *
     * @return
     */
    @Override
    public String getUsername() {
        return user.getUserName();
    }

}
